package com.gsmr.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.gsmr.util.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gsmr.entity.FACCH;
import com.gsmr.entity.PageBean;
import com.gsmr.entity.SACCH;
import com.gsmr.entity.SDCCH;
import com.gsmr.entity.SingleUser;
import com.gsmr.entity.TCH;
import com.gsmr.service.FACCHService;
import com.gsmr.service.InterferenceQueryService;
import com.gsmr.service.SACCHService;
import com.gsmr.service.SDCCHService;
import com.gsmr.service.TCHService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 *  Controller层
 * 
 * @author user
 *
 */
@Controller
@RequestMapping("/singleUser")
public class SingleUserController {

	@Resource
	private SDCCHService sdcchService;
	
	@Resource
	private FACCHService facchService;
	
	@Resource
	private SACCHService sacchService;
	
	@Resource
	private TCHService tchService;
	
	@Resource
	private InterferenceQueryService interferencequeryService;
	
	List<SingleUser> singleUserList;

	/**
	 * 分页条件查询SDCCH、FACCH、SACCH、TCH
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows, @RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime", required = false) String endTime, @RequestParam(value = "IMSI", required = false) String IMSI, @RequestParam(value = "MSISDN", required = false) String MSISDN,
			@RequestParam(value = "CTCS_ID", required = false) String CTCS_ID, @RequestParam(value = "UmType", required = false) String UmType, @RequestParam(value = "district", required = false) String district,
			@RequestParam(value = "kilometerStart", required = false) String kilometerStart, @RequestParam(value = "kilometerEnd", required = false) String kilometerEnd, SingleUser singleUser,
			@RequestParam(value = "search", required = false) String search, @RequestParam(value = "increase", required = false) String increase,@RequestParam(value = "recordId", required = false) String recordId,
			HttpServletResponse response) throws Exception {

		if (search == null)
			return;
			
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		String IMSI1 = "1";
		String IMSI2 = "1";
		String MSISDN1 = "1";
		String MSISDN2 = "1";
		List<String> traindata = new ArrayList<>();
		map.put("table_name", "train_info");
		if(!IMSI.equals("")) {
			IMSI1 = IMSI;
			map.put("IMSI", IMSI1);
			traindata = tchService.get_msisdn(map);
			if(traindata.size() != 0) {
				MSISDN1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!MSISDN.equals("")) {
			MSISDN1 = MSISDN;
			map.put("MSISDN", MSISDN1);
			traindata = tchService.get_imsi(map);
			if(traindata.size() != 0) {
				IMSI1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!CTCS_ID.equals("")) {
			map.put("CTCS_ID", CTCS_ID);
			traindata = tchService.get_imsi(map);
			if(traindata.size() >= 2) {
				IMSI1 = traindata.get(0);
				IMSI2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				IMSI1 = traindata.get(0);
			}
			traindata = tchService.get_msisdn(map);
			if(traindata.size() >= 2) {
				MSISDN1 = traindata.get(0);
				MSISDN2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				MSISDN1 = traindata.get(0);
			}
		}
		map.put("IMSI1", IMSI1);
		map.put("IMSI2", IMSI2);
		map.put("MSISDN1", MSISDN1);
		map.put("MSISDN2", MSISDN2);
		map.put("CTCS_ID", CTCS_ID);
		map.put("UmTypeAll", UmType);
		map.put("districtAll", district);
		map.put("kilometerStart", kilometerStart);
		map.put("kilometerEnd", kilometerEnd);
		map.put("recordId", recordId);

		if(UmType!=null&&!UmType.equals("")){
			String[] subUmType=UmType.split(",");
			List<String> subList=Arrays.asList(subUmType);
			map.put("UmType", subList);
		} else {
			map.put("UmType", "");
		}
		if (district != null && !district.equals("")) {
			String[] subdistrict = district.split(",");
			String[] frontID = new String[subdistrict.length];
			for (int i = 0; i < subdistrict.length; i++) {
				if(subdistrict[i].equals(""))
					continue;
				map.put("frontId", subdistrict[i]);
				map.put("table_name","bs_info");
				frontID[i] = interferencequeryService.get_frontId(map);
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
		} else {
			map.put("district", "");
		}
		
		Map<String, List<String>> tables = findTableNames(startTime, endTime, map);
		System.out.println(tables);
		List<String> table_names_sdcch = tables.get("table_names_sdcch");
		List<String> table_names_facch = tables.get("table_names_facch");
		List<String> table_names_sacch = tables.get("table_names_sacch");
		List<String> table_names_tch = tables.get("table_names_tch");
		
		List<SDCCH> sdcchList = new ArrayList<>();
		List<FACCH> facchList = new ArrayList<>();
		List<SACCH> sacchList = new ArrayList<>();
		List<TCH> tchList = new ArrayList<>();
		singleUserList = new ArrayList<>();
		singleUserList.clear();
		sdcchList.clear();
		facchList.clear();
		sacchList.clear();
		tchList.clear();

		if (table_names_sdcch != null && table_names_sdcch.size() > 0) {
			map.put("start", 0);
			map.put("size", pageBean.getPageSize());
			if(increase.equals("1")) {
				for (int i = table_names_sdcch.size() - 1; i >= 0 && sdcchList.size() < pageBean.getPageSize(); i--) {
					String tableName = table_names_sdcch.get(i);
					map.put("table_name", tableName);
					List<SDCCH> sub_sdcchList = sdcchService.findASC(map);
					sdcchList.addAll(sub_sdcchList);
				}
			} else {
				for (int i = 0; i < table_names_sdcch.size() && sdcchList.size() < pageBean.getPageSize(); i++) {
					String tableName = table_names_sdcch.get(i);
					map.put("table_name", tableName);
					List<SDCCH> sub_sdcchList = sdcchService.find(map);
					sdcchList.addAll(sub_sdcchList);
				}
			}
		}
		if (table_names_facch != null && table_names_facch.size() > 0) {
			map.put("start", 0);
			map.put("size", pageBean.getPageSize());
			if (increase.equals("1")) {
				for (int i = table_names_facch.size() - 1; i >= 0 && facchList.size() < pageBean.getPageSize(); i--) {
					String tableName = table_names_facch.get(i);
					map.put("table_name", tableName);
					List<FACCH> sub_facchList = facchService.findASC(map);
					facchList.addAll(sub_facchList);
				}
			} else {
				for (int i = 0; i < table_names_facch.size() && facchList.size() < pageBean.getPageSize(); i++) {
					String tableName = table_names_facch.get(i);
					map.put("table_name", tableName);
					List<FACCH> sub_facchList = facchService.find(map);
					facchList.addAll(sub_facchList);
				}
			}
		}
		if (table_names_sacch != null && table_names_sacch.size() > 0) {
			map.put("start", 0);
			map.put("size", pageBean.getPageSize());
			if (increase.equals("1")) {
				for (int i = table_names_sacch.size() - 1; i >= 0 && sacchList.size() < pageBean.getPageSize(); i--) {
					String tableName = table_names_sacch.get(i);
					map.put("table_name", tableName);
					List<SACCH> sub_sacchList = sacchService.findASC(map);
					sacchList.addAll(sub_sacchList);
				}
			} else {
				for (int i = 0; i < table_names_sacch.size() && sacchList.size() < pageBean.getPageSize(); i++) {
					String tableName = table_names_sacch.get(i);
					map.put("table_name", tableName);
					List<SACCH> sub_sacchList = sacchService.find(map);
					sacchList.addAll(sub_sacchList);
				}
			}
		}
		if (table_names_tch != null && table_names_tch.size() > 0) {
			map.put("start", 0);
			map.put("size", pageBean.getPageSize());
			if(increase.equals("1")) {
				for (int i = table_names_tch.size() - 1; i >= 0 && tchList.size() < pageBean.getPageSize(); i--) {
					map.put("table_name", table_names_tch.get(i));
					List<TCH> sub_tchList = tchService.findASC(map);
					tchList.addAll(sub_tchList);
				}
			} else {
				for (int i = 0; i < table_names_tch.size() && tchList.size() < pageBean.getPageSize(); i++) {
					map.put("table_name", table_names_tch.get(i));
					List<TCH> sub_tchList = tchService.find(map);
					tchList.addAll(sub_tchList);
				}
			}
		}
		  //赋予属性 20220930
		copyProperty(sdcchList, facchList, sacchList, tchList, singleUserList);
		if (!search.equals("3")) {
		SingleUserController.ListSort(singleUserList);
		}
		if (singleUserList.size() > pageBean.getPageSize() && increase.equals("1")) {
			singleUserList = singleUserList.subList(0, pageBean.getPageSize());
		} else if (singleUserList.size() > pageBean.getPageSize() && increase.equals("0")) {
			singleUserList = singleUserList.subList(singleUserList.size()-pageBean.getPageSize(), singleUserList.size());
		}
		/*
		 * 避免往前翻时第一页不足100条
		 */
		if (singleUserList.size() < pageBean.getPageSize() && increase.equals("0") && singleUserList.size() > 0) {
			String tmptime1=singleUserList.get(0).getStartTime(); 
			map.put("endTime",null);
			map.put("startTime",  DateUtil.longToString(Long.parseLong(tmptime1),"yyyyMMdd"));
			table_names_sdcch = sdcchService.findTableNames(map);
			table_names_facch = facchService.findTableNames(map);
			table_names_sacch = sacchService.findTableNames(map);
			table_names_tch = tchService.findTableNames(map);
			map.put("endTime", tmptime1);
			singleUserList.clear();
			sdcchList.clear();
			facchList.clear();
			sacchList.clear();
			tchList.clear();

			if (table_names_sdcch != null && table_names_sdcch.size() > 0) {
				map.put("start", 0);
				map.put("size", pageBean.getPageSize());

				if (increase.equals("1")) {
					for (int i = table_names_sdcch.size() - 1; i >= 0 && sdcchList.size() < pageBean.getPageSize(); i--) {
						String tableName = table_names_sdcch.get(i);
						map.put("table_name", tableName);
						List<SDCCH> sub_sdcchList = sdcchService.findASC(map);
						sdcchList.addAll(sub_sdcchList);
					}
				} else {
					for (int i = 0; i < table_names_sdcch.size() && sdcchList.size() < pageBean.getPageSize(); i++) {
						String tableName = table_names_sdcch.get(i);
						map.put("table_name", tableName);
						List<SDCCH> sub_sdcchList = sdcchService.find(map);
						sdcchList.addAll(sub_sdcchList);
					}
				}

			}
			if (table_names_facch != null && table_names_facch.size() > 0) {
				map.put("start", 0);
				map.put("size", pageBean.getPageSize());

				if (increase.equals("1")) {
					for (int i = table_names_facch.size() - 1; i >= 0 && facchList.size() < pageBean.getPageSize(); i--) {
						String tableName = table_names_facch.get(i);
						map.put("table_name", tableName);
						List<FACCH> sub_facchList = facchService.findASC(map);
						facchList.addAll(sub_facchList);
					}
				} else {
					for (int i = 0; i < table_names_facch.size() && facchList.size() < pageBean.getPageSize(); i++) {
						String tableName = table_names_facch.get(i);
						map.put("table_name", tableName);
						List<FACCH> sub_facchList = facchService.find(map);
						facchList.addAll(sub_facchList);
					}
				}
			}
			if (table_names_sacch != null && table_names_sacch.size() > 0) {
				map.put("start", 0);
				map.put("size", pageBean.getPageSize());

				if (increase.equals("1")) {
					for (int i = table_names_sacch.size() - 1; i >= 0 && sacchList.size() < pageBean.getPageSize(); i--) {
						String tableName = table_names_sacch.get(i);
						map.put("table_name", tableName);
						List<SACCH> sub_sacchList = sacchService.findASC(map);
						sacchList.addAll(sub_sacchList);
					}
				} else {
					for (int i = 0; i < table_names_sacch.size() && sacchList.size() < pageBean.getPageSize(); i++) {
						String tableName = table_names_sacch.get(i);
						map.put("table_name", tableName);
						List<SACCH> sub_sacchList = sacchService.find(map);
						sacchList.addAll(sub_sacchList);
					}
				}
			}
			if (table_names_tch != null && table_names_tch.size() > 0) {
				
				map.put("start", 0);
				map.put("size", pageBean.getPageSize());
				
				if(increase.equals("1")) {
					for (int i = table_names_tch.size() - 1; i >= 0 && tchList.size() < pageBean.getPageSize(); i--) {
						map.put("table_name", table_names_tch.get(i));
						List<TCH> sub_tchList = tchService.findASC(map);
						tchList.addAll(sub_tchList);
					}
				} else {
					for (int i = 0; i < table_names_tch.size() && tchList.size() < pageBean.getPageSize(); i++) {
						map.put("table_name", table_names_tch.get(i));
						List<TCH> sub_tchList = tchService.find(map);
						tchList.addAll(sub_tchList);
					}
				}
			}

			copyProperty(sdcchList, facchList, sacchList, tchList, singleUserList);

			if (!search.equals("3")) {
				SingleUserController.ListSort(singleUserList);
			}

			if(singleUserList.size()>pageBean.getPageSize()){
				singleUserList = singleUserList.subList(0, pageBean.getPageSize());
			}
		}
		int total = Integer.MAX_VALUE;
		JSONObject result = new JSONObject();
		
		JSONArray jsonArray = JSONArray.fromObject(singleUserList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);

	}

	/**
	 * 导出SDCCH与FACCH
	 */
	@RequestMapping("/export")
	public void export(@RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "recordId", required = false) String recordId, @RequestParam(value = "IMSI", required = false) String IMSI,
		@RequestParam(value = "MSISDN", required = false) String MSISDN, @RequestParam(value = "CTCS_ID", required = false) String CTCS_ID, @RequestParam(value = "endTime", required = false) String endTime, @RequestParam(value = "district", required = false) String district,
		HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String IMSI1 = "1";
		String IMSI2 = "1";
		String MSISDN1 = "1";
		String MSISDN2 = "1";
		List<String> traindata = new ArrayList<>();
		map.put("table_name", "train_info");
		if(!IMSI.equals("")) {
			IMSI1 = IMSI;
			map.put("IMSI", IMSI1);
			traindata = tchService.get_msisdn(map);
			if(traindata.size() != 0) {
				MSISDN1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!MSISDN.equals("")) {
			MSISDN1 = MSISDN;
			map.put("MSISDN", MSISDN1);
			traindata = tchService.get_imsi(map);
			if(traindata.size() != 0) {
				IMSI1 = traindata.get(0);
			}
			CTCS_ID = "1";
		}
		else if(!CTCS_ID.equals("")) {
			map.put("CTCS_ID", CTCS_ID);
			traindata = tchService.get_imsi(map);
			if(traindata.size() >= 2) {
				IMSI1 = traindata.get(0);
				IMSI2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				IMSI1 = traindata.get(0);
			}
			traindata = tchService.get_msisdn(map);
			if(traindata.size() >= 2) {
				MSISDN1 = traindata.get(0);
				MSISDN2 = traindata.get(1);
			}
			else if(traindata.size() == 1) {
				MSISDN1 = traindata.get(0);
			}
		}
		map.put("IMSI1", IMSI1);
		map.put("IMSI2", IMSI2);
		map.put("MSISDN1", MSISDN1);
		map.put("MSISDN2", MSISDN2);
		map.put("CTCS_ID", CTCS_ID);
		map.put("districtAll", district);
		map.put("recordId", recordId);

		if (district != null && !district.equals("")) {
			String[] subdistrict = district.split(",");
			String[] frontID = new String[subdistrict.length];
			for (int i = 0; i < subdistrict.length; i++) {
				if (subdistrict[i].equals(""))
					continue;
				map.put("frontId", subdistrict[i]);
				map.put("table_name", "bs_info");
				frontID[i] = interferencequeryService.get_frontId(map);
			}
			List<String> subList = Arrays.asList(frontID);
			map.put("district", subList);
		} else {
			map.put("district", "");
		}

		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		List<FACCH> facchList = new ArrayList<FACCH>();
		List<SACCH> sacchList = new ArrayList<SACCH>();
		List<TCH> tchList = new ArrayList<TCH>();

		Map<String, List<String>> tables = findTableNames(startTime, endTime, map);
		List<String> table_names_sdcch = tables.get("table_names_sdcch");
		List<String> table_names_facch = tables.get("table_names_facch");
		List<String> table_names_sacch = tables.get("table_names_sacch");
		List<String> table_names_tch = tables.get("table_names_tch");

	    List<SingleUser> singleUserList_all = new ArrayList<SingleUser>();

		List<SDCCH> sub_sdcchList = null;
		map.put("start", 0);
		if (table_names_sdcch != null) {
			for (int i = table_names_sdcch.size() - 1; i >= 0 && sdcchList.size() < ExcelUtil.maxExportRows; i--) {
				map.put("size", ExcelUtil.maxExportRows - sdcchList.size());
				map.put("table_name", table_names_sdcch.get(i));
				sub_sdcchList = sdcchService.findASC(map);
				if (sub_sdcchList != null && sub_sdcchList.size() > 0) {
					sdcchList.addAll(sub_sdcchList);
				}
			}
		}		
		List<FACCH> sub_facchList = null;
		if (table_names_facch != null) {
			for (int i = (table_names_facch.size() - 1); i >= 0 && facchList.size() <= ExcelUtil.maxExportRows; i--) {
				sub_facchList = null;
				map.put("size", ExcelUtil.maxExportRows - facchList.size());
				map.put("table_name", table_names_facch.get(i));
				sub_facchList = facchService.findASC(map);
				if (sub_facchList != null) {
					facchList.addAll(sub_facchList);
				}
			}
		}	
		List<SACCH> sub_sacchList = null;
		if (table_names_sacch != null) {
			for (int i = table_names_sacch.size() - 1; i >= 0 && sacchList.size() <= ExcelUtil.maxExportRows; i--) {
				map.put("size", ExcelUtil.maxExportRows - sacchList.size());
				map.put("table_name", table_names_sacch.get(i));
				sub_sacchList = sacchService.findASC(map);
				if (sub_sacchList != null) {
					sacchList.addAll(sub_sacchList);
				}
			}
		}	
		tchList.clear();
		List<TCH> sub_tchList = null;
		if (table_names_tch != null) {
			for (int i = table_names_tch.size() - 1; i >= 0 && tchList.size() <= ExcelUtil.maxExportRows; i--) {
				map.put("size", ExcelUtil.maxExportRows - tchList.size());
				map.put("table_name", table_names_tch.get(i));
				sub_tchList = tchService.findASC(map);
				if (sub_tchList != null) {
					tchList.addAll(sub_tchList);
				}
			}
		}

		copyProperty(sdcchList, facchList, sacchList, tchList, singleUserList_all);

		SingleUserController.ListSort(singleUserList_all);
		List<SingleUser> sub_singleUserList_all=singleUserList_all;
		if (singleUserList_all.size() > ExcelUtil.maxExportRows) {
			sub_singleUserList_all = singleUserList_all.subList(0, ExcelUtil.maxExportRows);
		}
		Workbook wb = new HSSFWorkbook();
		ExcelUtil.fillExcelData_SingleUser(sub_singleUserList_all, wb, headers);
		ResponseUtil.export(response, wb, "单用户" + FormatDate.formatDate() + ".xls");

	}
	
	private void copyProperty(List<SDCCH> sdcchList, List<FACCH> facchList, List<SACCH> sacchList, List<TCH> tchList, List<SingleUser> singleUserList) {

		for (SDCCH tmp_sdcch : sdcchList) {
			SingleUser tmpSingleUser = new SingleUser();
			tmpSingleUser.setCRCTest(tmp_sdcch.getCRC_ECC());
			tmpSingleUser.setCTCS_ID(tmp_sdcch.getCTCS_ID());
			tmpSingleUser.setData(tmp_sdcch.getSourceData());
			tmpSingleUser.setDataLength(tmp_sdcch.getDataLength());
			tmpSingleUser.setDirection(tmp_sdcch.getDirection());
			tmpSingleUser.setKilometer(tmp_sdcch.getKilometer());
			tmpSingleUser.setMSISDN(tmp_sdcch.getMSISDN());
			tmpSingleUser.setLogicChannel(tmp_sdcch.getLogicChannel());
			tmpSingleUser.setSiteName(tmp_sdcch.getSiteName());
			tmpSingleUser.setSpeed(tmp_sdcch.getSpeed());
			tmpSingleUser.setLEVEL(tmp_sdcch.getLEVEL());
			if(StringUtil.isNotEmpty(tmp_sdcch.getSNR())) {
				StringBuffer SNR=new StringBuffer();
				String[] SNRArry = tmp_sdcch.getSNR().split(" ");
				for (int i = 0; i < SNRArry.length; i++) {
					{
						double d = Double.parseDouble(SNRArry[i].trim());
						if(d>0) {
//						d=(Math.log10(d))*10;
							d = (double) Math.round(((Math.log10(d)) * 10) * 10) / 10;
							SNRArry[i] = String.valueOf((d));
							System.out.println("SNRArry[" + i + "]:=================" + SNRArry[i]);
							SNR.append(SNRArry[i] + " ");
						}else {
							SNR.append("/ ");
						}
					}
//					System.out.println(SNR);
					tmpSingleUser.setSNR(String.valueOf(SNR));
				}
			}
			tmpSingleUser.setQUALITY(tmp_sdcch.getQUALITY());
			tmpSingleUser.setStartTime(tmp_sdcch.getTimeStamp());
			tmpSingleUser.setSubType(tmp_sdcch.getMessage_TYPE());
			tmpSingleUser.setTrainNumber(tmp_sdcch.getENGINE_ID());
			tmpSingleUser.setRecordId(tmp_sdcch.getRecordId());
			tmpSingleUser.setIMSI(tmp_sdcch.getIMSI());
			singleUserList.add(tmpSingleUser);
		}
		for (FACCH tmp_facch : facchList) {
			SingleUser tmpSingleUser = new SingleUser();
			tmpSingleUser.setCRCTest(tmp_facch.getCRC_ECC());
			tmpSingleUser.setCTCS_ID(tmp_facch.getCTCS_ID());
			tmpSingleUser.setData(tmp_facch.getSourceData());
			tmpSingleUser.setDataLength(tmp_facch.getDataLength());
			tmpSingleUser.setDirection(tmp_facch.getDirection());
			tmpSingleUser.setKilometer(tmp_facch.getKilometer());
			tmpSingleUser.setMSISDN(tmp_facch.getMSISDN());
			tmpSingleUser.setLogicChannel(tmp_facch.getLogicChannel());
			tmpSingleUser.setSiteName(tmp_facch.getSiteName());
			tmpSingleUser.setSpeed(tmp_facch.getSpeed());
			tmpSingleUser.setStartTime(tmp_facch.getTimeStamp());
			tmpSingleUser.setLEVEL(tmp_facch.getLEVEL());
			if(StringUtil.isNotEmpty(tmp_facch.getSNR())) {
				StringBuffer SNR=new StringBuffer();
				String[] SNRArry = tmp_facch.getSNR().split(" ");
				for (int i = 0; i < SNRArry.length; i++) {
					{
						double d = Double.parseDouble(SNRArry[i].trim());
						if(d>0) {
//						d=(Math.log10(d))*10;
							d = (double) Math.round(((Math.log10(d)) * 10) * 10) / 10;
							SNRArry[i] = String.valueOf((d));
							System.out.println("SNRArry[" + i + "]:=================" + SNRArry[i]);
							SNR.append(SNRArry[i] + " ");
						}else {
							SNR.append("/ ");
						}
					}
//					System.out.println(SNR);
					tmpSingleUser.setSNR(String.valueOf(SNR));
				}
			}
			tmpSingleUser.setQUALITY(tmp_facch.getQUALITY());
			tmpSingleUser.setSubType(tmp_facch.getMessage_TYPE());
			tmpSingleUser.setTrainNumber(tmp_facch.getENGINE_ID());
			tmpSingleUser.setRecordId(tmp_facch.getRecordId());
			tmpSingleUser.setIMSI(tmp_facch.getIMSI());
			singleUserList.add(tmpSingleUser);
		}
		for (SACCH tmp_sacch : sacchList) {
			SingleUser tmpSingleUser = new SingleUser();
			tmpSingleUser.setCRCTest(tmp_sacch.getCRC_ECC());
			tmpSingleUser.setCTCS_ID(tmp_sacch.getCTCS_ID());
			tmpSingleUser.setData(tmp_sacch.getSourceData());
			tmpSingleUser.setDataLength(tmp_sacch.getDataLength());
			tmpSingleUser.setDirection(tmp_sacch.getDirection());
			tmpSingleUser.setKilometer(tmp_sacch.getKilometer());
			tmpSingleUser.setMSISDN(tmp_sacch.getMSISDN());
			tmpSingleUser.setLogicChannel(tmp_sacch.getLogicChannel());
			tmpSingleUser.setSiteName(tmp_sacch.getSiteName());
			tmpSingleUser.setSpeed(tmp_sacch.getSpeed());
			tmpSingleUser.setStartTime(tmp_sacch.getTimeStamp());
			tmpSingleUser.setSubType(tmp_sacch.getMessage_TYPE());
			tmpSingleUser.setLEVEL(tmp_sacch.getLEVEL());
			if(StringUtil.isNotEmpty(tmp_sacch.getSNR())) {
				StringBuffer SNR=new StringBuffer();
				String[] SNRArry = tmp_sacch.getSNR().split(" ");
				for (int i = 0; i < SNRArry.length; i++) {
					{
						double d = Double.parseDouble(SNRArry[i].trim());
						if(d>0) {
//						d=(Math.log10(d))*10;
							d = (double) Math.round(((Math.log10(d)) * 10) * 10) / 10;
							SNRArry[i] = String.valueOf((d));
							System.out.println("SNRArry[" + i + "]:=================" + SNRArry[i]);
							SNR.append(SNRArry[i] + " ");
						}else {
							SNR.append("/ ");
						}
					}
//					System.out.println(SNR);
					tmpSingleUser.setSNR(String.valueOf(SNR));
				}
			}
			tmpSingleUser.setQUALITY(tmp_sacch.getQUALITY());
			tmpSingleUser.setTrainNumber(tmp_sacch.getENGINE_ID());
			tmpSingleUser.setRecordId(tmp_sacch.getRecordId());
			tmpSingleUser.setIMSI(tmp_sacch.getIMSI());
			singleUserList.add(tmpSingleUser);
		}
		for (TCH tmp_tch : tchList) {
			SingleUser tmpSingleUser = new SingleUser();
			tmpSingleUser.setIMSI(tmp_tch.getIMSI());
			tmpSingleUser.setCRCTest(tmp_tch.getCRCTest());
			tmpSingleUser.setCTCS_ID(tmp_tch.getCTCS_ID());
			tmpSingleUser.setDirection(tmp_tch.getDirection());
			tmpSingleUser.setKilometer(tmp_tch.getKilometer());
			tmpSingleUser.setMSISDN(tmp_tch.getMSISDN());
			tmpSingleUser.setSiteName(tmp_tch.getSiteName());
			tmpSingleUser.setSpeed(tmp_tch.getSpeed());
			tmpSingleUser.setStartTime(tmp_tch.getTimeStamp());
			tmpSingleUser.setTrainNumber(tmp_tch.getENGINE_ID());
			tmpSingleUser.setRecordId(tmp_tch.getRecordId());
			// tmpSingleUser.setData(tmp_tch.getSourceData());
			// tmpSingleUser.setLogicChannel(tmp_tch.getLogicChannel());
			// tmpSingleUser.setSubType(tmp_tch.getMessage_TYPE());
			tmpSingleUser.setLEVEL(tmp_tch.getLEVEL());
			if(StringUtil.isNotEmpty(tmp_tch.getSNR())) {
				StringBuffer SNR=new StringBuffer();
				String[] SNRArry = tmp_tch.getSNR().split(" ");
				for (int i = 0; i < SNRArry.length; i++) {
					{
						double d = Double.parseDouble(SNRArry[i].trim());
						if(d>0) {
//						d=(Math.log10(d))*10;
							d = (double) Math.round(((Math.log10(d)) * 10) * 10) / 10;
							SNRArry[i] = String.valueOf((d));
							System.out.println("SNRArry[" + i + "]:=================" + SNRArry[i]);
							SNR.append(SNRArry[i] + " ");
						}else {
							SNR.append("/ ");
						}
					}
//					System.out.println(SNR);
					tmpSingleUser.setSNR(String.valueOf(SNR));
				}
			}
			tmpSingleUser.setQUALITY(tmp_tch.getQUALITY());
			tmpSingleUser.setData(tmp_tch.getTCH_FRAME());
			tmpSingleUser.setLogicChannel(tmp_tch.getMessage_TYPE());
			tmpSingleUser.setSubType(tmp_tch.getSignalName());
			if (tmp_tch.getDataLength() != null)
			tmpSingleUser.setDataLength(tmp_tch.getDataLength().toString());

			singleUserList.add(tmpSingleUser);
		}
	}

	private Map<String, List<String>> findTableNames(String startTime, String endTime, Map<String, Object> map) {

		// 当天00:00的时间戳
		Long earlyMorningTime = System.currentTimeMillis() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
		// 当前时间戳
		Long nowTime = System.currentTimeMillis();
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", DateUtil.longToString(Long.parseLong(startTime), "yyyyMMdd"));
		} else {
			map.put("startTime", DateUtil.longToString(earlyMorningTime, "yyyyMMdd"));
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", DateUtil.longToString(Long.parseLong(endTime), "yyyyMMdd"));
		} else {
			map.put("endTime", DateUtil.longToString(nowTime, "yyyyMMdd"));
		}

		Map<String, List<String>> tables = new HashMap<>();

		List<String> table_names_sdcch = sdcchService.findTableNames(map);
		List<String> table_names_facch = facchService.findTableNames(map);
		List<String> table_names_sacch = sacchService.findTableNames(map);
		List<String> table_names_tch = tchService.findTableNames(map);

		tables.put("table_names_sdcch", table_names_sdcch);
		tables.put("table_names_facch", table_names_facch);
		tables.put("table_names_sacch", table_names_sacch);
		tables.put("table_names_tch", table_names_tch);

		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		} else {
			map.put("startTime", null);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		} else {
			map.put("endTime", null);
		}
		return tables;
	}

	private String headers[] = { "触发时间", "IMSI", "MSISDN", "机车号", "小区名", "方向", "信令类型", "子类型", "CRC校验", "公里标", "速度", "数据长度", "LEVEL", "SNR", "QUALITY","数据内容", "记录号" };

	/**
	 * 导出当前页的数据
	 */
	@RequestMapping("/exportcurrentpage")
	public void exportcurrentpage(@RequestParam(value = "data") String data, HttpServletResponse response)
			throws Exception {

		List<SingleUser> singleUserList = new ArrayList<SingleUser>();
		if(data != null && !data.equals("null") && !data.equals("")) {
			JSONArray jsonArray=JSONArray.fromObject(data); 
			for(int i =0; i<jsonArray.size();i++) {
				SingleUser tmpSingleUser = new SingleUser();
				tmpSingleUser.setIMSI(jsonArray.getJSONObject(i).getString("IMSI"));
				tmpSingleUser.setCRCTest(jsonArray.getJSONObject(i).getString("CRCTest"));
				tmpSingleUser.setCTCS_ID(jsonArray.getJSONObject(i).getString("CTCS_ID"));
				tmpSingleUser.setData(jsonArray.getJSONObject(i).getString("data"));
				tmpSingleUser.setDataLength(jsonArray.getJSONObject(i).getString("dataLength"));
				tmpSingleUser.setDirection(jsonArray.getJSONObject(i).getString("direction"));
				tmpSingleUser.setKilometer(jsonArray.getJSONObject(i).getString("kilometer"));
				tmpSingleUser.setMSISDN(jsonArray.getJSONObject(i).getString("MSISDN"));
				tmpSingleUser.setLogicChannel(jsonArray.getJSONObject(i).getString("logicChannel"));
				tmpSingleUser.setSiteName(jsonArray.getJSONObject(i).getString("siteName"));
				tmpSingleUser.setSpeed(jsonArray.getJSONObject(i).getString("speed"));
				tmpSingleUser.setStartTime(jsonArray.getJSONObject(i).getString("startTime"));

				tmpSingleUser.setLEVEL(jsonArray.getJSONObject(i).getString("LEVEL"));
				tmpSingleUser.setSNR(jsonArray.getJSONObject(i).getString("SNR"));
				tmpSingleUser.setQUALITY(jsonArray.getJSONObject(i).getString("QUALITY"));

				tmpSingleUser.setSubType(jsonArray.getJSONObject(i).getString("subType"));
				tmpSingleUser.setTrainNumber(jsonArray.getJSONObject(i).getString("trainNumber"));
				tmpSingleUser.setSiteName(jsonArray.getJSONObject(i).getString("siteName"));
				tmpSingleUser.setRecordId(jsonArray.getJSONObject(i).getString("recordId"));
				singleUserList.add(tmpSingleUser);
			}
		}
		SingleUserController.ListSort(singleUserList);
		Workbook wb = new HSSFWorkbook();
		ExcelUtil.fillExcelData_SingleUser(singleUserList, wb, headers);
		ResponseUtil.export(response, wb, "单用户" + FormatDate.formatDate() + ".xls");

	}

	/**
	 * 判断是否存在指定PrimaryKey
	 */
	@RequestMapping("/existPrimaryKey")
	public void existUserName(String primaryKey, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		Map<String, Object> map = new HashMap<String, Object>();
		String frontProcessorId = primaryKey.substring(0, primaryKey.indexOf("-"));
		map.put("table_name", "sdcch_" + frontProcessorId);
		map.put("PrimaryKey", primaryKey);
		if (sdcchService.findByPrimaryKey(map) == null) {
			result.put("exist", false);
		} else {
			result.put("exist", true);
		}
		ResponseUtil.write(response, result);

	}

	/**
	 * 查找District列表
	 */
	@RequestMapping("/sdcchDistrictComboList")
	public void sdcchDistrictComboList(HttpServletResponse response) throws Exception {
		Map<String,Object> map=new HashMap<String,Object>();
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("id", -1);
		jsonObject.put("name", "");
		jsonArray.add(jsonObject);
		map.put("table_name","bs_info");
		List<String> bs_names=sdcchService.findDistricts(map);
		for(int i=0;i<bs_names.size();i++)
		{
			jsonObject.put("id", i);
			jsonObject.put("name",bs_names.get(i));
			jsonArray.add(jsonObject);
			
		}
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找Message_TYPE列表
	 */
	@RequestMapping("/sdcchMessage_TYPEComboList")
	public void sdcchMessage_TYPEComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findMessage_TYPEs(map);
				sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的Message_TYPE
		Map message_TYPE_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			message_TYPE_map.put(sdcchList.get(i).getMessage_TYPE(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = message_TYPE_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setMessage_TYPE(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找前置机列表
	 */
	@RequestMapping("/sdcchFrontProcessorIdComboList")
	public void sdcchFrontProcessorIdComboList(HttpServletResponse response) throws Exception {
		Map<String,Object> map=new HashMap<String,Object>();
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("id", -1);
		jsonObject.put("name", "");
		jsonArray.add(jsonObject);
		map.put("table_name","bs_info");
		List<String> FrontProcessorIds=sdcchService.findFrontProcessorIds(map);
		for(int i=0;i<FrontProcessorIds.size();i++)
		{
			jsonObject.put("id", i);
			jsonObject.put("name",FrontProcessorIds.get(i));
			jsonArray.add(jsonObject);
			
		}
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找IMSI列表
	 */
	@RequestMapping("/sdcchIMSIComboList")
	public void sdcchIMSIComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findIMSIs(map);
				sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的IMSI
		Map iMSI_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			iMSI_map.put(sdcchList.get(i).getIMSI(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = iMSI_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setIMSI(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找MSISDN列表
	 */
	@RequestMapping("/sdcchMSISDNComboList")
	public void sdcchMSISDNComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findMSISDNs(map);
				sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的MSISDN
		Map mSISDN_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			mSISDN_map.put(sdcchList.get(i).getMSISDN(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = mSISDN_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setMSISDN(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查找CTCS_ID列表
	 */
	@RequestMapping("/sdcchCTCS_IDComboList")
	public void sdcchCTCS_IDComboList(HttpServletResponse response) throws Exception {
		JSONArray jsonArray = new JSONArray();
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> table_names = sdcchService.findTableNames(map);
		List<SDCCH> sdcchList = new ArrayList<SDCCH>();
		if (table_names != null) {
			for (int i = 0; i < table_names.size(); i++) {
				map.put("table_name", table_names.get(i));
				List<SDCCH> sub_sdcchList = sdcchService.findCTCS_IDs(map);
				sdcchList.addAll(sub_sdcchList);
			}
		}
		
		// 过滤重复的CTCS_ID
		Map cTCS_ID_map = new HashMap<>();
		for (int i = 0; i < sdcchList.size(); i++) {
			cTCS_ID_map.put(sdcchList.get(i).getCTCS_ID(), 1);
		}
		Iterator<Map.Entry<String, String>> iterator = cTCS_ID_map.entrySet().iterator();
		sdcchList.clear();
		while (iterator.hasNext()) {
			Map.Entry<String, String> entry = iterator.next();
			SDCCH sdcch = new SDCCH();
			sdcch.setCTCS_ID(entry.getKey());
			sdcchList.add(sdcch);
		}
				
		JSONArray rows = JSONArray.fromObject(sdcchList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);

	}
	
	/**
	 * 对List中每个对象元素逆序排序
	 */
	private static void ListSort(List<SingleUser> list) {
		
		if (list == null || list.size() < 2) return;
		
		Collections.sort(list, new Comparator<SingleUser>() {
			@Override
			public int compare(SingleUser sf1, SingleUser sf2) {
				try {
					Long l1 = Long.parseLong(sf1.getStartTime());
					Long l2 = Long.parseLong(sf2.getStartTime());
					if (l1 < l2) {
						return -1;
					} else if (l1 > l2) {
						return 1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
	}
}